<template>
  <div>
    <el-button type="primary" @click="openAddBookDialog">新增书籍</el-button>
    <el-table :data="books" style="width: 100%">
      <el-table-column prop="name" label="书籍名称" />
      <el-table-column prop="author" label="作者" />
      <el-table-column label="操作">
        <template v-slot="scope">
          <el-button @click="handleDelete(scope.row.id)" type="danger" size="small">删除</el-button>
          <el-button @click="openUpdateBookDialog(scope.row)" type="warning" size="small">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- Add Book Dialog -->
    <el-dialog title="新增书籍" v-model="addDialogVisible">
      <el-form :model="bookForm">
        <el-form-item label="书籍名称" :rules="[{ required: true, message: '请输入书籍名称' }]">
          <el-input v-model="bookForm.name" />
        </el-form-item>
        <el-form-item label="章节一名" :rules="[{ required: true, message: '请输入章节名' }]">
          <el-input v-model="bookForm.sectionList[0].name" />
        </el-form-item>
        <el-form-item label="章节二名" :rules="[{ required: false, message: '请输入章节名' }]">
          <el-input v-model="bookForm.sectionList[1].name" />
        </el-form-item>
        <el-form-item label="章节三名" :rules="[{ required: false, message: '请输入章节名' }]">
          <el-input v-model="bookForm.sectionList[2].name" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAddBook">保存</el-button>
          <el-button @click="addDialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- Update Book Dialog -->
    <el-dialog title="编辑书籍" v-model="updateDialogVisible">
      <el-form :model="bookForm">
        <el-form-item label="书籍名称" :rules="[{ required: true, message: '请输入书籍名称' }]">
          <el-input v-model="bookForm.name" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleUpdateBook">保存</el-button>
          <el-button @click="updateDialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, reactive } from 'vue';
import { getBooks, addBook, deleteBook, updateBook } from '@/api/api';

export default {
  setup() {
    const sectionList = ref([
      { name: '' },
      { name: '' },
      { name: '' }
    ]);

    const books = ref([]);
    const addDialogVisible = ref(false);
    const updateDialogVisible = ref(false);
    const bookForm = reactive({
      name: '',
      categoryId: 1,
      image: 'http://example.com/image.jpg',
      sectionList: sectionList,
      year: '2024',
      status: 1
    });

    const fetchBooks = async () => {
      try {
        const response = await getBooks();
        console.log('Fetched Books:', response.data); // 调试输出
        books.value = response.data.data;
      } catch (error) {
        console.error('Error fetching books:', error);
      }
    };

    const handleAddBook = async () => {
      console.log('Adding Book:', bookForm); // 调试输出

      // 清理章节列表：移除没有填写章节名的章节
      const validSectionList = bookForm.sectionList.filter(section => section.name.trim() !== '');

      const bookData = { ...bookForm, sectionList: validSectionList };  // 只保留有效的章节
      console.log(bookData);
      try {
        const response = await addBook(bookData); // 使用处理后的数据
        if (response.data.code === 20011) {
          await fetchBooks();
          addDialogVisible.value = false;
        } else {
          console.error('Failed to add book:', response.data.message); // 错误提示
        }
      } catch (error) {
        console.error('Error adding book:', error);
      }
    };

    const handleDelete = async (id) => {
      console.log('Deleting Book ID:', id); // 调试输出
      try {
        const response = await deleteBook(id);
        if (response.data.code === 20021) {
          await fetchBooks();
        } else {
          console.error('Failed to delete book:', response.data.message); // 错误提示
        }
      } catch (error) {
        console.error('Error deleting book:', error);
      }
    };

    const openAddBookDialog = () => {
      bookForm.name = ''; // 重置书籍名称
      bookForm.sectionList = [ { name: '' }, { name: '' }, { name: '' } ]; // 重置章节列表
      addDialogVisible.value = true;
      console.log('openAddBookDialog', addDialogVisible.value);
    };

    const openUpdateBookDialog = (book) => {
      console.log('Editing Book:', book); // 调试输出
      bookForm.name = book.name;  // 填充书籍名称
      bookForm.sectionList = book.sectionList || [ { name: '' }, { name: '' }, { name: '' } ];  // 填充章节列表
      updateDialogVisible.value = true;
    };

    const handleUpdateBook = async () => {
      console.log('Updating Book:', bookForm); // 调试输出
      try {
        const response = await updateBook(bookForm);
        if (response.data.code === 20031) {
          await fetchBooks();
          updateDialogVisible.value = false;
        } else {
          console.error('Failed to update book:', response.data.message); // 错误提示
        }
      } catch (error) {
        console.error('Error updating book:', error);
      }
    };

    onMounted(() => {
      fetchBooks();
    });

    return {
      books,
      addDialogVisible,
      updateDialogVisible,
      bookForm,
      fetchBooks,
      handleAddBook,
      handleDelete,
      openAddBookDialog,
      openUpdateBookDialog,
      handleUpdateBook
    };
  }
};
</script>
